package com.bayss.core.service;


import com.alibaba.fastjson.JSON;
import com.bayss.core.constant.ResultMsg;
import com.bayss.core.entity.classify.Classify;
import com.bayss.core.entity.classify.ClassifyExample;
import com.bayss.core.entity.classify.ClassifyItem;
import com.bayss.core.entity.classify.ClassifyItemExample;
import com.bayss.core.entity.classify.mapper.ClassifyItemMapper;
import com.bayss.core.entity.classify.mapper.ClassifyMapper;
import com.bayss.core.entity.skuTag.SkuTagExample;
import com.bayss.core.entity.skuTag.mapper.SkuTagMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ClassifyService {

    private static Logger logger = LogManager.getLogger();

    @Autowired
    private ClassifyItemMapper classifyItemMapper;
    @Autowired
    private SkuTagMapper skuTagMapper;
    @Autowired
    private ClassifyMapper classifyMapper;


    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageInfo<Classify> findByPage(Integer page, Integer pageSize) {
        ClassifyExample example = new ClassifyExample();
        example.setOrderByClause("create_time desc");
        PageHelper.startPage(page, pageSize);
        PageInfo<Classify> result = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> classifyMapper.selectByExample(example));

        //items
        ClassifyItemExample classifyItemExample = new ClassifyItemExample();
        List<ClassifyItem> items = classifyItemMapper.selectByExample(classifyItemExample);
        Map<Integer, List<ClassifyItem>> map = items.stream().collect(Collectors.groupingBy(ClassifyItem::getClassifyId));
        for (Classify c : result.getList()) {
            c.setClassifyItems(map.get(c.getId()));
            //skuList
            setSkuTagList(c.getClassifyItems());
        }
        return result;
    }

    /**
     * 创建规格
     *
     * @param classify
     * @return
     */
    public ResultMsg createClassify(Classify classify) {
        if (StringUtils.isBlank(classify.getClassifyNameCn())
                || StringUtils.isBlank(classify.getClassifyNameEn())
                || StringUtils.isBlank(classify.getClassifyNameKo())) {
            return ResultMsg.fail(-1, "名称不能为空");
        }
        classify.setCreateTime(new Date());
        classify.setCode(Base64.getEncoder().encodeToString(classify.getClassifyNameCn().getBytes()));
        int r = classifyMapper.insertSelective(classify);
        return r > 0 ? ResultMsg.success() : ResultMsg.fail(-1, "创建失败");
    }


    /**
     * 创建规格明细
     *
     * @param classifyItem
     * @return
     */
    public ResultMsg createClassifyItem(ClassifyItem classifyItem) {
        if (StringUtils.isBlank(classifyItem.getItemNameCn())
                || StringUtils.isBlank(classifyItem.getItemNameEn())
                || StringUtils.isBlank(classifyItem.getItemNameKo())) {
            return ResultMsg.fail(-1, "名称不能为空");
        }

        classifyItem.setCreateTime(new Date());
        classifyItem.setCode(Base64.getEncoder().encodeToString(classifyItem.getItemNameCn().getBytes()));
        int r = classifyItemMapper.insertSelective(classifyItem);
        return r > 0 ? ResultMsg.success() : ResultMsg.fail(-1, "创建失败");
    }

    /**
     * 更新规格
     *
     * @param classify
     * @return
     */
    public int updateClassify(Classify classify) {
        classify.setCode(Base64.getEncoder().encodeToString(classify.getClassifyNameCn().getBytes()));
        logger.info(classify.getClassifyNameCn() + "-> " + classify.getCode());
        return classifyMapper.updateByPrimaryKeySelective(classify);
    }

    /**
     * 更新规格明细
     *
     * @param classifyItem
     * @return
     */
    public int updateClassifyItem(ClassifyItem classifyItem) {
        classifyItem.setCode(Base64.getEncoder().encodeToString(classifyItem.getItemNameCn().getBytes()));
        return classifyItemMapper.updateByPrimaryKeySelective(classifyItem);
    }

    /**
     * 删除规格
     *
     * @param id
     * @return
     */
    public int deleteClassify(Integer id) {
        return classifyMapper.deleteByPrimaryKey(id);
    }


    /**
     * 删除规格明细
     *
     * @param id
     * @return
     */
    public int deleteClassifyItem(Integer id) {
        return classifyItemMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询规格明细
     *
     * @param id
     * @return
     */
    public ClassifyItem findClassifyItemById(Integer id) {
        return classifyItemMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询规格明细list
     *
     * @param classifyById
     * @return
     */
    public List<ClassifyItem> findClassifyItemByClassifyId(Integer classifyById) {
        ClassifyItemExample classifyItemExample = new ClassifyItemExample();
        ClassifyItemExample.Criteria criteria = classifyItemExample.createCriteria();
        criteria.andClassifyIdEqualTo(classifyById);
        List<ClassifyItem> list = classifyItemMapper.selectByExample(classifyItemExample);

        //skuList
        setSkuTagList(list);
        return list;
    }

    /**
     * 规格明细添加skuTag属性
     *
     * @param list
     */
    private void setSkuTagList(List<ClassifyItem> list) {
        if (list == null) {
            return;
        }
        for (ClassifyItem item : list) {
            if (StringUtils.isEmpty(item.getSkuTags())) {
                continue;
            }
            SkuTagExample skuTagExample = new SkuTagExample();
            SkuTagExample.Criteria skuTagExampleCriteria = skuTagExample.createCriteria();
            List<Integer> skuIds = Arrays.asList(item.getSkuTags().split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
            skuTagExampleCriteria.andIdIn(skuIds);
            item.setSkuTagList(skuTagMapper.selectByExample(skuTagExample));
        }
    }

    /**
     * 根据id查询规格
     *
     * @param id
     * @return
     */
    public Classify findClassifyById(Integer id) {
        return classifyMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据规格明细code查询规格明细
     *
     * @param code
     * @return
     */
    public ClassifyItem findClassifyItemByCode(String code) {
        ClassifyItemExample classifyItemExample = new ClassifyItemExample();
        classifyItemExample.createCriteria().andCodeEqualTo(code);
        List<ClassifyItem> classifyItems = classifyItemMapper.selectByExample(classifyItemExample);
        if (CollectionUtils.isEmpty(classifyItems)) {
            return null;
        } else {
            return classifyItems.get(0);
        }
    }

    /**
     * 查询规格list
     *
     * @param type
     * @return
     */
    public List<Classify> findClassifyList(Integer type) {
        // classify
        ClassifyExample classifyExample = new ClassifyExample();
        if (type != null) {
            classifyExample.createCriteria().andTypeEqualTo(type.byteValue());
        }
        List<Classify> list = classifyMapper.selectByExample(classifyExample);
        //items
        ClassifyItemExample classifyItemExample = new ClassifyItemExample();
        List<ClassifyItem> items = classifyItemMapper.selectByExample(classifyItemExample);
        Map<Integer, List<ClassifyItem>> map = items.stream().collect(Collectors.groupingBy(ClassifyItem::getClassifyId));

        for (Classify c : list) {
            c.setClassifyItems(map.get(c.getId()));
        }
        return list;
    }

    /**
     * 查询规格根据code
     *
     * @param code
     * @return
     */
    public Classify findClassifyByCode(String code) {
        ClassifyExample classifyExample = new ClassifyExample();
        classifyExample.createCriteria().andCodeEqualTo(code);
        List<Classify> classifies = classifyMapper.selectByExample(classifyExample);
        if (CollectionUtils.isEmpty(classifies)) {
            return null;
        } else {
            return classifies.get(0);
        }
    }

    public List<ClassifyItem> findItemsByClassifyId(Integer classifyId) {
        ClassifyItemExample classifyItemExample = new ClassifyItemExample();
        classifyItemExample.createCriteria().andClassifyIdEqualTo(classifyId);
        List<ClassifyItem> items = classifyItemMapper.selectByExample(classifyItemExample);
        return items;
    }


    public List<Classify> findClassifyAndClassifyItemByType(Integer type) {
        ClassifyExample classifyExample = new ClassifyExample();
        classifyExample.createCriteria().andTypeEqualTo(type.byteValue());
        List<Classify> classifies = classifyMapper.selectByExample(classifyExample);
        if (!CollectionUtils.isEmpty(classifies)) {
            for (Classify classify : classifies) {
                List<ClassifyItem> items = findClassifyItemByClassifyId(classify.getId());
                classify.setClassifyItems(items);
            }
            return classifies;
        }
        return null;
    }


    /**
     * 查找规格
     *
     * @param spuCode
     * @return
     */
    public List<Classify> findSpec(String spuCode) {
        String[] classifyArr = spuCode.replace("spu_", "").split("_");
        ArrayList<String> classifyArrList = Lists.newArrayList(classifyArr);
        classifyArrList.remove(0);
        List<Classify> list = Lists.newArrayList();
        for (String classifyCode : classifyArrList) {
            Classify classify = findClassifyByCode(classifyCode);
            list.add(classify);
            List<ClassifyItem> items = findClassifyItemByClassifyId(classify.getId());
            classify.setClassifyItems(items);
        }
        return list;
    }

    /*public static void main(String[] args) {
        System.out.println(Base64.getEncoder().encodeToString("其他".getBytes()));
        System.out.println(new String(Base64.getDecoder().decode("Pz8/Pz8/")));
    }*/
}
